package com.hippoframework.container;
import java.io.File;

import com.hippoframework.mvc.DispatcherServlet;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.AprLifecycleListener;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

/**
 * 内嵌tomcat助手类
 *
 * @author TylerW
 * @date 4/16/2020 3:55 PM
 */
@Getter
@Setter
public class EmbedTomcat {

    public static String WEBAPP_PATH = "src/main";

    @SneakyThrows
    public static void run() {
        // tomcat的端口号
        int port = 8081;
        // tomcat的字符编码集
        String code = "UTF-8";
        // 拦截请求路径
        String hinderURL = "/test";
        // 请求转发路径
        String shiftURL = "/test";
        // tomcat对象
        Tomcat tomcat = new Tomcat();
        // 设置Connector
        Connector conn = tomcat.getConnector();
        conn.setPort(port);
        conn.setURIEncoding(code);

        tomcat.setBaseDir("."); // tomcat 信息保存在项目下

        StandardContext myCtx = (StandardContext) tomcat
            .addWebapp(hinderURL, System.getProperty("user.dir") + File.separator + WEBAPP_PATH);

        myCtx.setReloadable(false);
        // 上下文监听器
        myCtx.addLifecycleListener(new AprLifecycleListener());

        // 注册servlet
        tomcat.addServlet(shiftURL, "dispatcherServlet", new DispatcherServlet());
        // servlet mapping
        myCtx.addServletMappingDecoded(shiftURL, "dispatcherServlet");

        tomcat.start();
        tomcat.getServer().await();


    }


}
